// pages/mine/qrcode/index.js
const service = require('../../service/other')
const BASE_LEFT = 80
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvas: null,
    downLoadData: '',
    qrcodeData: '', //图片的base64地址
    username: '',
    avatar: '',
    goodsName: '',
    goodsImage: '',
    goodsPrice: '',
    qrData: '',
    bacUrl:'',
    p1Url:'',
    p2Url:'',
    p4Url:''
  },

  drawPoster(img) { // 绘制海报
    const _this = this;
    const ctx = wx.createCanvasContext('poster');
    console.log(this.data.p1Url,this.data.p2Url,this.data.p4Url,this.data.bacUrl)
    // const bacUrl = '../../images/poster_back.png';
    // const p1 = '../../images/p1.png';
    // const p2 = '../../images/p2.png';
    // const p3 = '../../images/p3.png';
    // const p4 = '../../images/p4.png';
    const bacUrl = this.data.bacUrl;
    const p1 = this.data.p1Url;
    const p2 = this.data.p2Url;
    const p3 = '../../images/p3.png';
    const p4 = this.data.p4Url;
    const avatar = this.data.avatar;
    const nickname = this.data.username;
    const goodsName = this.data.goodsName;
    const goodsImage = this.data.goodsImage;
    const goodsPrice = '￥ ' + this.data.goodsPrice;
    const len = Math.floor(goodsName.length / 10);
    let list = [];
    for (let i = 0; i < len; i++) {
      let str = goodsName.slice(i * 10, 10 * (i + 1))

      list.push(str)
    };
    console.log(list)
   // 绘制背景图
   ctx.drawImage(bacUrl, 0, 0, 350, 550);
   // 绘制log
   ctx.drawImage(p1, 24, 24, 104, 41);
   // 绘制广告语
   ctx.drawImage(p2, 141, 34, 121, 22);
   // 绘制背景图片
   ctx.drawImage(p3, 22, 71, 307, 433);
   // 绘制底部服务说明
   ctx.drawImage(p4, 26, 511, 295, 16);
   // 绘制用户信息
   ctx.drawImage(avatar, 47, 90, 42, 42);
    ctx.setFillStyle('#2D2D2D');
    ctx.font = 'normal bold 13px sans-serif';
    ctx.fillText(nickname, 103, 105);

    ctx.font = 'normal normal 10px sans-serif';
    // ctx.fillText('全国首家大学生创业平台', 103, 130);
    // 绘制商品信息
    ctx.drawImage(goodsImage, 47, 144, 265, 266);
    ctx.setFillStyle('#ffffff');
    ctx.font = 'normal bold 16px sans-serif';
    ctx.fillText(goodsPrice, 63, 427);
    ctx.setFillStyle('#2d2d2d');
    ctx.font = 'normal bold 10px sans-serif';

    for (let j = 0; j < list.length; j++) {
      ctx.fillText(list[j], 47, 438 + ((j + 1) * 16));
    };
    // 绘制二维码图片
    ctx.drawImage(img, 222, 413, 75, 75);
    ctx.setFillStyle('#B9B9B9');
    ctx.font = 'normal bold 6px sans-serif';
    ctx.fillText('长按扫码去购买', 234, 500)
    ctx.draw(true, () => {
      wx.hideLoading({
        success: (res) => {},
      })
    })
  },
  saveImg() {
    wx.canvasToTempFilePath({
      canvasId: 'poster',
      x: 0,
      y: 0,
      width: 350,
      height: 550,
      success({
        tempFilePath
      }) {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success() {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail() {
            wx.showToast({
              title: '保存失败',
              icon: 'none'
            })
          }
        })
      }
    })
  },
  getCanvas(base) {
    const _this = this;
    let query = wx.createSelectorQuery();
    query.select('#posterWrap')
      .fields({
        node: true,
        size: true
      })
      .exec(res => {
        console.log(res)
        let canvas = res[0].node;
        let img = canvas.createImage();
        img.src = base;
        img.onload = r => {
          setTimeout(() => {
            _this.drawPoster(img);
          }, 1500)
        }

      })
  },
  base64src(base64data, cb) {
    const fsm = wx.getFileSystemManager();
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
    if (!format) {
      return (new Error('ERROR_BASE64SRC_PARSE'));
    }
    const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.${format}`;
    const buffer = wx.base64ToArrayBuffer(bodyData);
    fsm.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success() {
        cb(filePath);
      },
      fail() {
        return (new Error('ERROR_BASE64SRC_WRITE'));
      },
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    service.getgoodsPosterall(res => {
      console.log(res)
      let [ { url: url1 }, { url: url2 }, { url: url3 }, { url: url4 } ] = res.data;
      wx.getImageInfo({
        src: url1,
        success ({ path }) {
          self.setData({
            p1Url: path
          })
        }
      });
      wx.getImageInfo({
        src: url2,
        success ({ path }) {
          self.setData({
            p2Url: path
          })
        }
      });
      wx.getImageInfo({
        src: url3,
        success ({ path }) {
          self.setData({
            bacUrl: path
          })
        }
      });
      wx.getImageInfo({
        src: url4,
        success ({ path }) {
          self.setData({
            p4Url: path
          })
        }
      });

      
    wx.showLoading({
      title: '海报生成中...',
    });
    let goodsDetail = JSON.parse(options.param)


    const _this = this;
    let info = wx.getStorageSync('userInfo')
    wx.getImageInfo({
      src: info.headPic,
      success({
        path
      }) {
        _this.setData({
          avatar: path,
          username: info.wechatNick
        })
      }
    });

    wx.getImageInfo({
      src: goodsDetail.goodsImage,
      success({
        path
      }) {
        _this.setData({
          goodsName: goodsDetail.goodsName,
          goodsImage: path,
          goodsPrice: goodsDetail.goodsPrice
        })
      }
    });
    service.getGoodsQrCode(goodsDetail.id, ({
      data
    }) => {
      // _this.getCanvas(data)
      _this.base64src(data, res => {
        setTimeout(() => {
          _this.drawPoster(res)
        }, 1000)
      })
      // _this.setData({
      //   qrData: data
      // }, () => {
      //   setTimeout(() => {
      //     _this.drawPoster();
      //   }, 1500)
      // })

    })
    })
   

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */

  initCanvas() {
    wx.showLoading({
      title: '生成图片中',
    })
    const query = wx.createSelectorQuery()
    query.select('#qrCodeId')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        let goodsDetail = this.data.goodsDetail
        let id = goodsDetail.id;
        service.getGoodsQrCode(id, ({
          data
        }) => {

          this.drawCanvas(res, data, goodsDetail)
        })
      })
  },

  drawCanvas(res, qr, goodsDetail) {

    const dpr = wx.getSystemInfoSync().pixelRatio
    const width = res[0].width * dpr
    const height = res[0].height * dpr

    const canvas = res[0].node

    this.setData({
      canvas: canvas
    })
    canvas.width = width
    canvas.height = height


    const ctx = canvas.getContext('2d')
    // ctx.scale(dpr, dpr)

    //绘制背景图片
    let goodsImage = canvas.createImage()

    goodsImage.src = goodsDetail.goodsImage
    goodsImage.onload = (res) => {
      //绘制二维码背景
      let rectW = 250 * dpr
      let rectH = 250 * dpr
      let rectX = (width - rectW) / 2
      let rectY = (height - rectH) / 2
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, width, height)
      ctx.drawImage(goodsImage, rectX, 300, rectW, rectY)
      //绘制二维码图片
      let qrImage = canvas.createImage()
      qrImage.src = qr
      // qrImage.width = 200
      // qrImage.height = 200
      qrImage.onload = (res) => {

        //绘制二维码背景
        let rectW = 250 * dpr
        let rectH = 250 * dpr
        let rectX = (width - rectW) / 2
        let rectY = (height - rectH) / 2
        //设置阴影
        ctx.shadowOffsetX = 20
        ctx.shadowOffsetY = 20
        ctx.shadowColor = 'rgba(201,201,201,0.3)'
        ctx.shadowBlur = 100

        //绘制二维码图片
        let qrImageW = 100 * dpr
        let qrImageH = 100 * dpr
        let qrImageX = (width - qrImageW) / 2
        let qrImageY = 300 + rectY + 20 + 80
        ctx.drawImage(qrImage, qrImageX, qrImageY, qrImageW, qrImageH)

        let storeName = '全民直播商小程序商城'
        ctx.font = `normal bold ${20 * dpr}px Arial`;
        ctx.fillStyle = "#2D2D2D"
        let storeMeasure = ctx.measureText(storeName)
        let storeX = (width - storeMeasure.width) / 2
        let storeY = 300 + rectY + qrImageH + 20 + 120 + 80
        ctx.fillText(storeName, storeX, storeY);

        let storeNameTip = '长按扫描二维码，进入商城'
        ctx.font = ` ${13 * dpr}px Arial`;
        ctx.fillStyle = "#2D2D2D"
        let storeTipMeasure = ctx.measureText(storeNameTip)
        let storeTipX = (width - storeTipMeasure.width) / 2
        let storeTipY = 300 + rectY + qrImageH + 20 + 120 + 100 + 80
        ctx.fillText(storeNameTip, storeTipX, storeTipY);




        //绘制文字
        let fontText = `${goodsDetail.goodsName}`
        fontText = fontText.substr(0, 18) + '...'


        ctx.font = `${16 * dpr}px Arial`;
        ctx.fillStyle = "#707070"

        let measure = ctx.measureText(fontText)
        let fontX = BASE_LEFT || (width - measure.width) / 2
        let fontY = 150
        ctx.fillText(fontText, fontX, fontY);
        let fontText2 = `￥ ${goodsDetail.goodsPrice}`
        ctx.font = `normal bold ${20 * dpr}px Arial`;
        ctx.fillStyle = "#FE3F3F"

        let measure2 = ctx.measureText(fontText2)
        let fontX2 = BASE_LEFT
        let fontY2 = 250
        ctx.fillText(fontText2, fontX2, fontY2);

        ctx.save()

        let fontText4 = '图片长按保存至手机后,即可将图片分享至朋友圈'
        ctx.font = 'normal bold 32px Arial';
        ctx.fillStyle = "#B9B9B9"

        let measure4 = ctx.measureText(fontText4)
        let fontX4 = (width - measure4.width) / 2
        let fontY4 = height - 100
        ctx.fillText(fontText4, fontX4, fontY4);
        ctx.restore()
        wx.hideLoading({})

      }
      qrImage.onerror = (err) => {
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '加载图片失败了!',
              icon: 'none'
            })
          },
        })
      }
    }
  },

  wxSageFileToLocal(base64) {

  },

  saveImage() {
    //当前页面绘制图片
    let _this = this
    let canvas = this.data.canvas
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      // width: 600,
      // height: 922,
      // destWidth: 600,
      // // quality: 1,
      // destHeight: 922,
      canvas,
      success({
        tempFilePath
      }) {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success() {
            wx.showToast({
              title: '保存成功!',
            })
          },
          fail(err) {
            console.log(22222, err)
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          showCancel: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          showCancel: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          }
        })
      },
    }, this)
  },
  strokeRoundRect(cxt, x, y, width, height, radius, lineWidth, strokeColor) {
    //圆的直径必然要小于矩形的宽高          
    if (2 * radius > width || 2 * radius > height) {
      return false;
    }

    cxt.save();
    cxt.translate(x, y);
    //绘制圆角矩形的各个边  
    this.drawRoundRectPath(cxt, width, height, radius);
    cxt.lineWidth = lineWidth || 2; //若是给定了值就用给定的值否则给予默认值2  
    cxt.strokeStyle = strokeColor || "#ffffff";
    cxt.fill();
    cxt.stroke();
    cxt.restore();
  },
  drawRoundRectPath(cxt, width, height, radius) {
    cxt.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI  
    cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

    //矩形下边线  
    cxt.lineTo(radius, height);

    //左下角圆弧，弧度从1/2PI到PI  
    cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

    //矩形左边线  
    cxt.lineTo(0, radius);

    //左上角圆弧，弧度从PI到3/2PI  
    cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

    //上边线  
    cxt.lineTo(width - radius, 0);

    //右上角圆弧  
    cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

    //右边线  
    cxt.lineTo(width, height - radius);
    cxt.closePath();
  },

  onShareAppMessage: function () {

  }
})